function [fun, grad] = PL_penalty_CTV(beta, varargin)
% [fun, grad] = PL_penalty_CTV(beta, varargin)
% 
% PL_penalty_CTV computes the Colour Total Variation [1].
%
% See also: PL_penalty_parallel, PL_penalty_Nambu, PL_penalty
%
% [1] P. Blomgren and T.F. Chan, 
%     Color TV: Total Variation Methods for Restoration of Vector-Valued Images,
%     IEEE Transactions on Image Processing, vol. 7, no. 3, pp. 304–309, 1998
%
% 2013-07-25 --------------------------------------------------------------
% 
% Matthias J. Ehrhardt
% CMIC, University College London, UK
% 
% matthias.ehrhardt.11@ucl.ac.uk
% 
% -------------------------------------------------------------------------

    if iscell(varargin{1})
        K = length(varargin{1});
        input = varargin{1};
    else
        K = length(varargin);
        input = varargin;
    end
    
    N = cell(K,1);
    TV = zeros(K,1);
    
    if nargout > 1
        c = numel(input{1});
        grad = zeros(c* K,1);
    end
    
    for k = 1 : K
        % calulate the gradient
        G = Gradient(input{k}, 'symmetric', 'central', 1, 0);
        % and store its norm
        N{k} = Norm_3(G, beta);
        
        TV(k) = sum(beta * N{k}(:));
    end
           
    CTV = sqrt(sum(TV.^2));
        
    if nargout > 1
        for k = 1 : K
            kappa = beta./N{k} * TV(k) / CTV;

            grad((k-1) * c + (1 : c)) = - Diffusion(kappa, input{k});
        end      
    end
    
    fun = CTV;
end